﻿function BindAutoComplete(url, selector, parameter, useCache) {
    var queueCache = [];
    $(selector).autocomplete({
        minLength: 0,
        delay: 500,
        source: function (request, response) {
            var term = request.term;
            if (useCache) {
                for (var i = 0; i < queueCache.length; i++) {
                    if (term in queueCache[i]) {
                        response(queueCache[i][term]);
                        return;
                    }
                }
            }
            if (!parameter) { parameter = {}; parameter.pageIndex = 0; parameter.pageSize = GetPageSize(); }
            parameter.query = term;
            $.post(url, parameter, function (data, status) {
                if (useCache) {
                    var cache = {}; cache[term] = data;
                    if (queueCache.length >= 20) { queueCache.pop(); }
                    queueCache.unshift(cache);
                }
                response(data);
            }, "json");
        }
    });
}

function GetPageSize(selector) {
    if (isNaN(selector)) {
        selector = "#select_page_size";
    }
    var strPageSize = $(selector).val();
    if (strPageSize) {
        return parseInt(strPageSize);
    }
    return 20;
}